// 测试数据格式验证
const testData = {
  // 模拟后端返回的SKU数据
  skuStockList: [
    {
      id: 1,
      spData: '[{"key":"颜色","value":"红色"},{"key":"尺寸","value":"XL"}]',
      price: 100,
      stock: 50
    },
    {
      id: 2,
      spData: '[{"key":"颜色","value":"蓝色"},{"key":"尺寸","value":"L"}]',
      price: 95,
      stock: 30
    }
  ],

  // 模拟selectProductAttr初始状态
  selectProductAttr: [
    {
      id: 1,
      name: "颜色",
      handAddStatus: 0,
      inputList: "红色,蓝色,绿色,黑色",
      values: [],
      options: []
    },
    {
      id: 2,
      name: "尺寸",
      handAddStatus: 1,
      inputList: "",
      values: [],
      options: []
    }
  ]
}

// 模拟restoreProductAttrValues方法的逻辑
function testRestoreProductAttrValues(skuStockList, selectProductAttr) {
  const allAttributes = {}
  
  skuStockList.forEach(sku => {
    if (sku.spData && sku.spData.trim()) {
      try {
        const spData = JSON.parse(sku.spData)
        if (Array.isArray(spData)) {
          spData.forEach(attr => {
            if (attr.key && attr.value) {
              if (!allAttributes[attr.key]) {
                allAttributes[attr.key] = new Set()
              }
              allAttributes[attr.key].add(attr.value)
            }
          })
        }
      } catch (e) {
        console.error('解析spData失败:', sku.spData, e)
      }
    }
  })

  selectProductAttr.forEach(targetAttr => {
    const key = targetAttr.name
    if (allAttributes[key] && allAttributes[key].size > 0) {
      targetAttr.values = Array.from(allAttributes[key])
      
      if (targetAttr.handAddStatus === 1) {
        if (!targetAttr.options) {
          targetAttr.options = []
        }
        const currentOptions = new Set(targetAttr.options)
        targetAttr.values.forEach(value => {
          currentOptions.add(value)
        })
        targetAttr.options = Array.from(currentOptions)
      } else {
        const predefinedOptions = (targetAttr.inputList || '').split(',').filter(v => v.trim())
        targetAttr.values = targetAttr.values.filter(value => 
          predefinedOptions.includes(value)
        )
      }
    }
  })
  
  return selectProductAttr
}

// 运行测试
console.log('原始selectProductAttr:', JSON.stringify(testData.selectProductAttr, null, 2))
const result = testRestoreProductAttrValues(testData.skuStockList, testData.selectProductAttr)
console.log('恢复后的selectProductAttr:', JSON.stringify(result, null, 2))

// 验证结果
console.log('\n验证结果:')
console.log('颜色属性值:', result[0].values)  // 应该包含 ["红色", "蓝色"]
console.log('尺寸属性值:', result[1].values)  // 应该包含 ["XL", "L"]
console.log('尺寸属性选项:', result[1].options)  // 应该包含 ["XL", "L"]